﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
using System.Globalization;
using iTFF.WPF.View;
using iTFF.WPF.ViewModel;
using iTFF.WPF.CP;
using System.Threading;
using System.Windows.Threading;
using System.Text;

namespace iTFF.WPF
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // add an exception 
            DispatcherUnhandledException += App_DispatcherUnhandledException;

            // upgrade settings if needed
            if (Settings.Default.CallUpgrade)
            {
                Settings.Default.Upgrade();
                Settings.Default.CallUpgrade = false;
            }

            // Set the correct culture.
            Thread.CurrentThread.CurrentCulture =
                Thread.CurrentThread.CurrentUICulture =
                    ControlPanel.Instance.UserCultureInfo;

            // Ensure the current culture passed into bindings is the OS culture.
            // By default, WPF uses en-US as the culture, regardless of the system settings.
            FrameworkElement.LanguageProperty.OverrideMetadata(
              typeof(FrameworkElement),
              new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            MainWindow window = new MainWindow();

            // create the instance for the GlobalHotKeyControlPanel, it needs a Window for its Handle
            ControlPanel.Instance.Initialize(window);

            // Create the ViewModel to which 
            // the main window binds.
            var viewModel = new MainWindowViewModel();

            // When the ViewModel asks to be closed, 
            // close the window.
            EventHandler handler = null;
            handler = delegate
            {
                viewModel.RequestClose -= handler;
                window.Close();
            };
            viewModel.RequestClose += handler;

            // Allow all controls in the window to 
            // bind to the ViewModel by setting the 
            // DataContext, which propagates down 
            // the element tree.
            window.DataContext = viewModel;

            window.Show();

        }

        /// <summary>
        /// Just shows a message box when an unexpected error occurs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            var message = new StringBuilder("Oops! An unexpected error occured.\r\n You should leave a bug report at this adress: http://itff.codeplex.com/WorkItem/List.aspx \r\n" +
                "Here is a the error that you should copy (Ctrl + C) in your message : \r\n");

            var exception = e.Exception;

            while (exception != null)
            {
                message.Append("\r\n\r\n");
                message.Append(exception.Message);
                message.Append("\r\n");
                message.Append(exception.StackTrace);

                exception = exception.InnerException;
            }

            e.Handled = true;

            MessageBox.Show(message.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);

        }

        protected override void OnExit(ExitEventArgs e)
        {

            // dispose all control panels (including hotkeys)
            ControlPanel.Instance.Dispose();

            // save settings
            Settings.Default.Save();

            base.OnExit(e);
        }

    }
}
